<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 上部新增按钮 -->
      <el-row>
        <el-button type="primary" @click="addFn">+新增角色</el-button>
      </el-row>
      <!-- 卡片阴影---table表格 -->
      <el-card>
        <el-table
          :data="tableData"
          style="width: 100%"
          :row-class-name="tableRowClassName"
        >
          <el-table-column
            type="index"
            label="序号"
            width="180"
          />
          <el-table-column
            prop="title"
            label="角色名称"
            width="180"
          />
          <el-table-column
            prop="description"
            label="角色描述"
          />
          <el-table-column prop="" label="操作">
            <template v-slot="{row}">
              <el-button type="primary" @click="apportion(row.id)">分配权限</el-button>
              <el-button type="success" @click="editFn(row.id)">编辑</el-button>
              <el-button type="info" @click="delFn(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 底部分页器 -->
      <el-pagination
        align="center"
        :current-page="num"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <!-- 添加--编辑框 -->
      <el-dialog :title="form.id? '编辑角色': '新增角色' " :visible="dialogFormVisible" @close="closeFn">
        <el-form ref="roleForm" :model="form" :rules="rules">
          <el-form-item label="角色名称" label-width="180" prop="title">
            <el-input v-model="form.title" autocomplete="off" />
          </el-form-item>
          <el-form-item label="角色描述" label-width="180" prop="description">
            <el-input v-model="form.description" autocomplete="off" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeFn">取 消</el-button>
          <el-button type="primary" @click="confirmFn">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 树形结构--分配权限 -->
      <el-dialog title="分配权限" :visible="dialogVisible" :close-on-click-modal="false" @close="closePerFn">
        <el-tree
          ref="trees"
          default-expand-all
          :data="treeData"
          :props="{label: 'title'}"
          show-checkbox
          :check-strictly="true"
          node-key="id"
        />
        <div slot="footer" class="dialog-footer">
          <el-button @click="closePerFn">取 消</el-button>
          <el-button type="primary" @click="confirmPerFn">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRoleList, addRole, getRoleCount, getRoleDetail, updataRole, deleteRole, getPermissions } from '@/api/roles'
import { listToTree } from '@/utils/index'
export default {
  data() {
    return {
      curId: null,
      dialogFormVisible: false, // 显示隐藏弹窗,
      dialogVisible: false,
      num: 0, // 开始获取的位置
      page: 1, // 显示第几页
      pagesize: 5, // 每页显示多少条数据
      total: 0, // 数据总条数
      // 表格数据
      tableData: [],
      form: {
        title: '',
        description: ''
      },
      rules: {
        title: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '角色名称不能超过10个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' },
          { min: 1, max: 30, message: '角色描述不能超过30个字符', trigger: 'blur' }
        ]
      },
      treeData: [], // 权限列表
      permIds: [] // 选中的权限
    }
  },
  created() {
    this.getRoleLists() // 进入页面获取角色列表
    this.getRoleCounts() // 获取角色数量
    // const res = await getPermissions()
    // this.treeData = listToTree(res, '0')
    this.getPermissionss()
  },
  methods: {
    // 确认分配权限按钮
    async confirmPerFn() {
      // 获取选中的权限的id集合
      const res = await this.$refs.trees.getCheckedKeys()
      // 调用接口添加权限
      await updataRole({
        id: this.curId,
        permissions: res
      })
      this.$message.success('添加成功')
      // 关闭弹窗
      this.closePerFn()
    },
    // 关闭权限弹窗
    closePerFn() {
      this.dialogVisible = false
      // 关闭弹窗重置选中的选项
      this.$refs.trees.setCheckedKeys([])
      this.permIds = []
      // 刷新页面
      this.getRoleLists()
    },
    // 点击分配权限
    async apportion(id) {
      // 弹出提示框
      this.curId = id
      this.dialogVisible = true
      // 调用接口获角色列表
      const res = await getRoleDetail(id)
      console.log(127, res)
      // 获取角色已有权限
      res.permissions.forEach(item => {
        return this.permIds.push(item.id)
      })
      // 实现数据回显
      this.$refs.trees.setCheckedKeys(this.permIds)
    },
    // 获取所有权限列表
    async getPermissionss() {
      const res = await getPermissions()
      this.treeData = listToTree(res, '0')
      console.log(137, res)
    },
    // 点击删除
    delFn(id) {
      this.$confirm('是否确定删除角色?', '删除角色', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        console.log('确认删除', id)
        // 调用接口删除角色
        await deleteRole(id)
        // 删除成功 --提示
        this.$message.success('删除成功')
        // 刷新页面
        this.getRoleLists()
      }).catch(() => {
        console.log('取消删除')
      })
    },
    // 点击编辑
    async editFn(id) {
      this.dialogFormVisible = true
      // 调用接口-数据回显
      this.form = await getRoleDetail(id)
    },
    // 点击确定
    async confirmFn() {
      // 点击确认,验证规则
      this.$refs.roleForm.validate()
      // 判断用户是处于添加角色还是编辑角色
      if (this.form.id) {
        // id存在则是编辑角色
        await updataRole(this.form)
      } else {
        // 添加角色
        await addRole(this.form)
      }
      // 添加成功提示
      this.$message.success('操作成功')
      // 刷新页面
      this.getRoleLists()
      // 关闭弹窗
      this.closeFn()
    },
    // 关闭弹窗
    closeFn() {
      this.dialogFormVisible = false
      // 清空表单数据
      this.form = {
        title: '',
        description: ''
      }
      // 清除验证规则
      this.$refs.roleForm.resetFields()
      // 刷新页面
      this.getRoleLists()
    },
    // 点击添加角色---弹出dialog框
    addFn() {
      this.dialogFormVisible = true
    },
    // 获取角色数量
    async getRoleCounts() {
      this.total = await getRoleCount()
      this.getRoleLists()
    },
    // 获取角色列表
    async getRoleLists() {
      const res = await getRoleList({
        _limit: this.pagesize,
        _start: this.num
      })
      this.tableData = res
      console.log(84, res)
      // 获取角色数量
      this.total = await getRoleCount()
    },
    // 改变每页显示条数改变时触发
    handleSizeChange(val) {
      console.log('改变每页显示条数改变时触发', val)
      this.pagesize = val
      this.getRoleLists()
    },
    // 当前页数改变时触发
    handleCurrentChange(val) {
      console.log('当前页数改变时触发', val)
      this.num = (val - 1) * this.pagesize
      this.getRoleLists()
    },
    // table 每行的颜色
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return 'warning-row'
      } else if (rowIndex === 3) {
        return 'success-row'
      }
      return ''
    }
  }
}
</script>

<style lang="scss" scoped>
.el-row{
  .el-button{
margin-bottom: 20px;
  }
}
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
</style>

